package com.ruoyi.aitcommon.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import com.ruoyi.common.utils.StringUtils;

public class AspectjUtils {
//	日志中参数的条数
	private static final int ARGCOUNT = 3;
	
	/**
	 * 获取切面的方法全名
	 * @param joinPoint 切面点
	 * @return
	 */
	public static String getMehtodName(JoinPoint joinPoint) {
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		return className + "." + methodName + "()";
	}
	
	/**
	 * 拼接参数和返回的字符串
	 * @param var
	 * @param len
	 * @return 格式化后的字符串
	 */
	public static String getLogStr(Object var,int len) {
		if(var==null) return "";
		int cnt=0;
		
		String retstr="";
		StringBuilder sb=new StringBuilder();
		if(var instanceof List) {
//			参数是列表
			sb.append("\r\n");
			List<?> list=(List<?>)var;
			for(Object item:list) {
				cnt++;
				if(item instanceof Map){
//					如果是Map,用JSON格式输出
					JSONObject json=new JSONObject((Map)item);
					sb.append(json.toString()+"\r\n");
				}else{
					sb.append(item.toString()+"\r\n");
				}
				if(cnt==ARGCOUNT) {
					sb.append("more....,total:"+list.size()+"\r\n");
					break;
				}
			}
			retstr=sb.toString();
		}else if(var instanceof Map){
//			参数是Map,转成JSON输出
			JSONObject json=new JSONObject((Map)var);
			retstr=json.toString();
		}else
			retstr=var.toString();

//		返回处理
		return StringUtils.substring(retstr,0, len);
	}
	
	/**
	 * 切面方法是否存在注解，如果存在就获取
	 * @param joinPoint 切面连接点
	 * @param clazz 注解类
	 * @return 注解对象
	 */
	public static <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> clazz) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(clazz);
		}
		return null;
	}
	/**
	 * 获取切面的参数名称
	 * @param joinPoint
	 * @return
	 */
	public static String[] getParmNames(JoinPoint joinPoint) {
		List<String> retlist=new ArrayList<String>();
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		Parameter[] parameters = method.getParameters();
		for (Parameter parameter : parameters) {
			retlist.add(parameter.getName());
		}
		return (String[]) retlist.toArray(new String[0]);
	}
	
	/**
	 * 获取切面的参数值
	 * @param joinPoint
	 * @return
	 */
	public static Object[] getParmValues(JoinPoint joinPoint) {
		return joinPoint.getArgs();
	}
}
